<!-- 为他人报名页面 -->
<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import { fetchRegisterPersonListAPI } from '@/apis/fetchRegisterPersonList'
import { useUserInfoStore } from '@/store/userInfo'
import { registerForSomeoneAPI } from '@/apis/registerForSomeone'
import router from '@/router'

const userInfoStore = useUserInfoStore()

// 班级 id
const classId = ref('')
// 班级名称
const className = ref('')

// // 分页联系人列表数据
// const { dataList, loading, loadingMore, noMore, loadMore } = useLoadMore<LoadMoreData<Person>>(
//   fetchContacts,
//   { isNoMore: d => d?.list.length === d?.total },
// )

// 搜索结果数据
const { searchText, isOpenSearch, searching, searchResult, fetchSearchResult } = useSearch<Person>(search as any)

onLoad((options) => {
  if (options && options.class_id && options.class_name) {
    classId.value = options.class_id
    className.value = options.class_name
  }
  else { uni.showToast({ title: '页面加载错误：未获取到班级id', icon: 'none' }) }
})
onReachBottom(() => fetchSearchResult())

// 渲染的列表，如果处于搜索状态，则展示搜索结果，否则展示列表数据
// const finalList = computed(() => {
//   if (isOpenSearch.value)
//     return searchResult.value
//   else
//     return dataList.value
// })

// “加载更多”的状态
// const loadMoreStatus = computed(() => {
//   if (loadingMore.value)
//     return 'loading'
//   else if (noMore.value)
//     return 'nomore'
//   else
//     return 'loadmore'
// })

/**
 * @description 分页服务函数
 */
// async function fetchContacts(d?: LoadMoreData<Person>): Promise<LoadMoreData<Person>> {
//   // 当前页数
//   const _page = d?.page ? d.page + 1 : 1

//   const res = await fetchRegisterPersonListAPI({
//     page: _page.toString(),
//     limit: '10',
//   }, userInfoStore.userInfo!.token!)

//   return {
//     list: res.data?.data.data || [],
//     page: _page,
//     total: res.data?.data.total || 9999,
//   }
// }

/**
 * @description 搜索服务函数
 */
async function search() {
  const res = await fetchRegisterPersonListAPI({
    page: '1',
    limit: '100',
    keywords: searchText.value.length > 0 ? searchText.value : undefined,
  }, userInfoStore.userInfo!.token!)
  return res.data!
}

// 是否显示确认报名弹窗
const isShowDialog = ref(false)

// 即将报名的同学名字
const registerClassmate = ref({
  name: '',
  id: '',
})

/**
 * @description 搜索框文本更新时触发
 */
const handleSearch = useDebounceFn((keyword: string) => {
  searchText.value = keyword
  fetchSearchResult()
}, 500)

/**
 * @description 点击“为他报名”时触发
 */
function handleRegisterForSomeone(person: Person) {
  registerClassmate.value.id = person.id.toString()
  registerClassmate.value.name = person.username
  isShowDialog.value = true
}

/**
 * @description 二次确认后触发，执行为他人报名的逻辑
 */
async function handleConfirmRegisterForSomeone() {
  try {
    isShowDialog.value = false
    // loading.value = true
    const res = await registerForSomeoneAPI({
      id: classId.value,
      user_id: registerClassmate.value.id,
    }, userInfoStore.userInfo!.token!)
    // loading.value = false

    if (res.data?.code === 1) {
      registerClassmate.value = { id: '', name: '' }
      router.replace({
        name: 'submitSuccess',
        params: { type: '报名' },
      })
    }
    else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
  }
  catch (err) {
    uni.showToast({ title: JSON.stringify(err), icon: 'none' })
  }
}
</script>

<template>
  <view class="bg-#F8FAFE">
    <view class="bg-white">
      <Spacer height="48" />
      <uv-search
        bg-color="#F3F3F3"
        placeholder="请输入人员姓名/电话查询"
        search-icon-size="52rpx"
        color="#333333"
        placeholder-color="#A7A7A7"
        height="80rpx"
        margin="0 25rpx"
        :show-action="false"
        @change="handleSearch"
        @focus="isOpenSearch = true"
        @blur="isOpenSearch = false"
      />
      <Spacer height="15" />
    </view>
    <view class="bg-white py-20rpx">
      <view class="mx-25rpx text-24rpx text-#333333 leading-32rpx">
        查询结果({{ searchResult.length }})
      </view>
      <Spacer height="6" />
      <PersonItem
        v-for="person in searchResult"
        :key="person.id"
        :avatar="person.avatar"
        :name="person.username"
        :position="person.duties"
      >
        <button
          class="flex items-center justify-center rounded-full bg-#0037AE px-20rpx py-14rpx text-24rpx text-white font-semibold leading-32rpx"
          hover-class="bg-#3266D9"
          @tap="handleRegisterForSomeone(person)"
        >
          为他报名
        </button>
      </PersonItem>
      <!-- 加载更多 -->
      <!-- <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" /> -->
    </view>
    <Spacer height="20" />
  </view>
  <PageDefault v-if="searchResult.length === 0">
    {{ searchText.length > 0 ? '暂无联系人' : '请搜索' }}
  </PageDefault>
  <uv-loading-page :loading="searching" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />

  <uv-overlay :show="isShowDialog" @tap="isShowDialog = false">
    <uv-transition mode="zoom-in" :show="isShowDialog">
      <view class="relative h-screen w-screen">
        <view class="absolute left-50% top-50% -translate-50%">
          <Dialog
            title="立即报名"
            cancel-label="再想想"
            confirm-label="确认报名"
            @cancel="isShowDialog = false"
            @confirm="handleConfirmRegisterForSomeone"
          >
            <view class="text-center">
              您即将为<text class="px-8rpx text-#0037AE">
                {{ registerClassmate.name }}
              </text>报名
              <br>
              {{ className }}
              <br>
              该课程，请立即确认
            </view>
          </Dialog>
        </view>
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'registerForSomeone'
style:
  navigationBarTitleText: '为他人报名'
layout: 'custom'
</route>
